<template>
  <div>
    <div class="filter">
      <button
        v-for="(tab, index) in tabs"
        :key="index"
        :class="{ active: currentTab === tab.value }"
        @click="changeTab(tab.value)"
      >
        {{ tab.label }} <span v-if="tab.count !== null">{{ tab.count }}</span>
      </button>
    </div>

    <div
      v-for="exam in paginatedExams"
      :key="exam.stu_exam_id"
      class="exam-card"
      @click="navigateToExamDetail(exam)"
    >
      <div v-if="exam.is_submit" class="completed-watermark">
        <img src="@/assets/picture/isSubmit.png" alt="已完成" />
      </div>
      <div class="exam-content">
        <div class="exam-header">
          <span class="badge" :class="statusBadgeClass(exam.status)">
            {{ statusLabel(exam.status) }}
          </span>
          <p style="font-weight:bold;">{{ exam.paper_title }}</p>
        </div>
        <p>老师: {{ exam.username }}</p>
        <div style="display:flex; font-size: 12px; color: gray;">
          <p style="margin-right: 10px;">开始时间: {{ exam.start_time }}</p>
          <p style="margin-right: 10px;">结束时间: {{ exam.end_time }}</p>
          <p style="margin-right: 10px;">考试时长: {{ exam.during_time ? exam.during_time + '分钟' : '不限时' }}</p>
        </div>
      </div>
    </div>

    <PagiNation :currentPage="currentPage" :totalPages="totalPages" @page-change="handlePageChange" />
  </div>
</template>
<script>
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { fetchStuExams } from '@/services/api'; // 注意换成新方法
import PagiNation from '@/components/PagiNation.vue';
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
  name: 'StuExams',
  components: { PagiNation },
  props: {
    classId: {
      type: [String, Number],
      required: true,
    },
  },
  setup(props) {
    const userId = localStorage.getItem('id');
    const router = useRouter();
    const currentTab = ref('全部考试');
    const currentPage = ref(1);
    const itemsPerPage = 8;
    const exams = ref([]);
    const tabs = ref([
      { label: '全部考试', value: '全部考试', count: null },
      { label: '进行中', value: 1, count: null },
      { label: '已截止', value: 2, count: null },
    ]);

    const loadExams = async () => {
      try {
        const response = await fetchStuExams(props.classId, null, userId);
        if (response.data.status === 1) {
          exams.value = response.data.data.map(exam => ({
            ...exam,
          }));

          tabs.value.forEach(tab => {
            if (tab.value === '全部考试') {
              tab.count = exams.value.length;
            } else {
              tab.count = exams.value.filter(exam => exam.status === tab.value).length;
            }
          });
        }
      } catch (error) {
        console.error('加载考试失败:', error);
      }
    };

    const filteredExams = computed(() => {
      if (currentTab.value === '全部考试') {
        return exams.value;
      } else {
        return exams.value.filter(exam => exam.status === currentTab.value);
      }
    });

    const paginatedExams = computed(() => {
      const start = (currentPage.value - 1) * itemsPerPage;
      const end = start + itemsPerPage;
      return filteredExams.value.slice(start, end);
    });

    const totalPages = computed(() => {
      return Math.ceil(filteredExams.value.length / itemsPerPage);
    });

    const changeTab = (tabValue) => {
      currentTab.value = tabValue;
      currentPage.value = 1;
    };

    const handlePageChange = (newPage) => {
      currentPage.value = newPage;
    };

   const navigateToExamDetail = (exam) => {
      const activeExamId = localStorage.getItem('activeExamId');
      const isSubmitted = exam.is_submit;
      const hasConfirmed = sessionStorage.getItem(`exam_confirmed_${exam.exam_id}`);
      if (exam.status === 1 && !isSubmitted && activeExamId && activeExamId !== String(exam.exam_id)) {
        ElMessage.warning('您有未完成的考试，请先提交后再进入其他考试');
        return;
      }

      if (exam.status === 1 && !isSubmitted && !hasConfirmed) {
        ElMessageBox.confirm(
          '进入考试后，若未提交将无法再进入其他考场，且离开考试页面将继续计时，请及时保存作答。',
          '进入考试确认',
          {
            confirmButtonText: '确认进入',
            cancelButtonText: '取消',
            type: 'warning',
          }
        ).then(() => {
           sessionStorage.setItem(`exam_confirmed_${exam.exam_id}`, 'true');
          // 用户点击确认
          localStorage.setItem('activeExamId', exam.exam_id);
          localStorage.setItem('start_time', new Date().toISOString());

          localStorage.setItem('currentExamStatus', exam.status);
          localStorage.setItem('currentExamTitle', exam.paper_title);
          localStorage.setItem('currentPaperId', exam.paper_id);
          localStorage.setItem('currentExamId', exam.exam_id);
          localStorage.setItem('lastExamClick', Date.now().toString());
          localStorage.setItem('is_submit', exam.is_submit);
          localStorage.setItem('during_time', exam.during_time);
          localStorage.setItem('stu_exam_id', exam.stu_exam_id);

          router.push({ name: 'StuPaperPreview', params: { examId: exam.exam_id, semesterId: props.classId } });
        }).catch(() => {
          // 用户点击取消，无需处理
        });
      } else {
        // 已提交或已截止的考试直接跳转
        localStorage.setItem('currentExamStatus', exam.status);
        localStorage.setItem('currentExamTitle', exam.paper_title);
        localStorage.setItem('currentPaperId', exam.paper_id);
        localStorage.setItem('currentExamId', exam.exam_id);
        localStorage.setItem('lastExamClick', Date.now().toString());
        localStorage.setItem('is_submit', exam.is_submit);
        localStorage.setItem('during_time', exam.during_time);
        localStorage.setItem('stu_exam_id', exam.stu_exam_id);

        router.push({ name: 'StuPaperPreview', params: { examId: exam.exam_id, semesterId: props.classId } });
      }
    };
    const statusLabel = (status) => {
      switch (status) {
        case 1: return '进行中';
        case 2: return '已截止';
        default: return '未知状态';
      }
    };

    const statusBadgeClass = (status) => {
      switch (status) {
        case 1: return 'badge-in-progress';
        case 2: return 'badge-closed';
        default: return 'badge-new';
      }
    };

    onMounted(() => {
      loadExams();
    });

    return {
      currentTab,
      tabs,
      currentPage,
      totalPages,
      exams,
      filteredExams,
      paginatedExams,
      statusLabel,
      statusBadgeClass,
      changeTab,
      handlePageChange,
      navigateToExamDetail,
    };
  },
};
</script>



<style scoped>
/* 新建考试菜单 */
.new-question-button {
  background-color: #244382;
  color: white;
  padding: 10px 15px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.new-question-menu {
    width: 74px;
    position: absolute;
    margin-top: -15px;
    right: 11.5vw;
    z-index: 10;
    background-color: white;
    border: 1px solid #ddd;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
    border-radius: 4px;
    padding: 10px;
    display: flex;
    flex-direction: column;
    gap: 10px;
    align-items: center;
}

.new-question-menu span {
  cursor: pointer;
  padding: 5px 0;
  color: gray;
  transition: color 0.3s;
}

.new-question-menu span:hover {
  color: #244382;
}
/* 与作业页面相似的样式 */
.filter {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.filter button {
  background: none;
  border: none;
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
  color: #333;
  transition: background-color 0.3s, color 0.3s;
}

.filter button.active {
  color: #244382;
  border-bottom: 2px solid #244382;
  font-weight: bold;
}

.filter .create-button {
  margin-left: auto;
  background-color: #244382;
  color: #fff;
  padding: 10px 15px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.filter .create-button:hover {
  background-color: #376edc;
}

.exam-card {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  position: relative;
  transition: transform 0.3s;
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
}

.exam-card:hover {
  transform: translateY(-5px);
  background-color: #f0f0f0;
}

.exam-checkbox {
  margin-right: 15px;
  margin-top: 5px;
  cursor: pointer;
  margin-top: 20px;
}

.exam-content {
  flex: 1;
}

.exam-header {
  display: flex;
  align-items: center;
  gap: 15px;
  position: relative;
}

.badge {
  display: inline-block;
  padding: 5px 10px;
  border-radius: 12px;
  font-size: 14px;
}


.badge-in-progress {
  background-color: #d6ffdb;
  color: #3b995c;
}

.badge-closed {
  background-color: #ffd6d6;
  color: #d9534f;
}

.exam-actions {
  margin-left: auto;
  display: flex;
  gap: 10px;
  position: absolute;
  right: 0;
  top: 0;
}

.edit-button,
.delete-button {
  background-color: transparent;
  border: none;
  cursor: pointer;
  color: #244382;
  font-size: 14px;
  transition: color 0.3s;
}

.edit-button:hover,
.delete-button:hover {
  color: #1e3661;
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.close-btn {
  cursor: pointer;
  font-size: 24px;
}

.dialog-actions {
  margin: 30px 0px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
.selected-paper-info {
  font-size: 14px;
  color: #666;
  margin-right: auto;
  margin-left: 20px;
}

.confirm-button {
  font-size: 15px;
  margin-right: 20px;
  background-color: #125AA2;
  color: #fff;
  padding: 10px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}
.confirm-button:hover {
  background-color: #3987d4;
}
.bac-button {
  font-size: 15px;
  background-color: #eee;
  color: rgb(80, 80, 80);
  border: rgb(95, 95, 95);
  padding: 10px 16px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}
.bac-button:hover{
  background-color:rgb(212, 212, 212) !important;
}
.dialog-content {
  background: white;
  border-radius: 8px;
  width: 80%;
  max-width: 1200px;
  height: 80vh;
  padding: 20px;
  display: flex;
  flex-direction: column;
  /* 添加滚动条 */
  overflow-y: scroll; /* 外层容器隐藏滚动 */
}

.dialog-content::v-deep .exam-bank-container { /* 穿透样式到子组件 */
  flex: 1;
  overflow-y: auto;
  padding: 10px 0;
}
.badge-new{
    background-color: #f3e4b7f0;
  color:  #dda90ff0;
}
/* 已完成水印 */
.completed-watermark {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 10;
}

.completed-watermark img {
  width: 50px;  /* 设置水印图片的大小 */
  height: auto;
}
</style>
